package com.github.gin.spring.boot.errorhandling.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by FSTMP on 2016/12/15.
 */
@ControllerAdvice
public class BaseController extends ResponseEntityExceptionHandler  {

    @ExceptionHandler
    String handleControllerException(HttpServletRequest request, Model model, Throwable ex) {
        HttpStatus status = getStatus(request);
        System.out.println(new ResponseEntity(ex.getMessage(), status));
        model.addAttribute("errorMsg","error");
        return "error/500";
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

}
